package com.travel.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.travel.authserver.feign.MemberFeignService;
import com.travel.authserver.vo.SocialUser;
import com.travel.common.utils.HttpUtils;
import com.travel.common.utils.R;
import com.travel.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    //http://auth.travel.com/oauth2.0/weibo/success?code=7cab9a014391aadca25e4b45644e4871
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session)throws Exception{
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", "1762652394");
        map.put("client_secret", "34da17e1e8e05aa967b32fb85bc164e9");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.travel.com/oauth2.0/weibo/success");
        map.put("code", code);

        //1. 根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(), map);

        //2. 处理
        if(response.getStatusLine().getStatusCode() == 200){
            //获取到了 accessToken
            //将返回的数据转为实体类的字符串
            String json = EntityUtils.toString(response.getEntity());
            //再将字符串转为 社交登录的用户对象
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //判断当前是哪个社交用户
            //2.1 当前用户如果是第一次进入网站，自动注册进来(为当前社交用户生成一个会员信息账号，以后这个社交账号就对应这个会员)
            //登录或者注册这个社交用户
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if(oauthLogin.getCode() == 0){
                MemberRespVo data = oauthLogin.getData(new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功，用户：{}",data.toString());
                //1. 第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问那个网站就会带上这个网站的cookie
                //子域之间：travel.com auth.travel.com order.travel.com
                //发卡的时候(指为父域名定域名)，即使是子域系统发的卡，也能让父域直接使用
                //TODO 1.默认发的令牌，session=xxxx，作用域：当前域（解决子域session共享问题）
                //TODO 2.使用JSON的序列化方式来序列化对象数据到redis中
                session.setAttribute(LOGIN_USER,data);
                //2. 登录成功就跳回首页
                return "redirect:http://travel.com";
            }else {
                return "redirect:http://auth.travel.com/login.html";
            }
        }else{
            return "redirect:http://auth.travel.com/login.html";
        }
    }
}
